package com.sh.learn.itcast.javaadvanced.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;

public class ProxyUtil {
	
	/**
	 * 抽象动态代理的过程
	 */
	public static Object getProxy(final Object target, final Advice advice){
		// 模板模式
		Object proxyInstance = Proxy.newProxyInstance(
			Collection.class.getClassLoader(), 
			// new Class[]{Collection.class}, 
			target.getClass().getInterfaces(),
			new InvocationHandler(){
				// ArrayList target = new ArrayList();
				@Override
	            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					Object returnVal = null;
					try {
						// long beginTime = System.currentTimeMillis();
						advice.beforeMethod(target, method, args);
						returnVal = method.invoke(target, args);
						// long endTime = System.currentTimeMillis();
			            advice.afterMethod(target, method, args);
			           
                    } catch (Exception e) {
                    	advice.catchException(target, method, args, e);
                    }
					return returnVal;
	            }
			}
		);
		return proxyInstance;
	}

}
